package com.foling.system.controller.mall;

import com.foling.system.common.Result;
import com.foling.system.entity.*;
import com.foling.system.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

@Controller
public class OrderItemController {
    @Autowired
    ProductService productService;

    //跳转到购物车界面
    @GetMapping("/shop-cart")
    public String cartListPage(HttpServletRequest request,
                               HttpSession httpSession) {
        //获取购物车
        Cart cart = (Cart) httpSession.getAttribute("cart");
        List<CartItem> cartItems = cart.getItems();
        request.setAttribute("myShoppingCartItems", cartItems);
        return "mall/cart";
    }
    //添加到购物车
    @PostMapping("/shop-cart")
    @ResponseBody
    public Result saveOrderItem(@RequestBody CartItem cartItem,
                                HttpSession httpSession) {
        //获取购物车
        Cart cart = (Cart) httpSession.getAttribute("cart");
        //如果没有购物车，产生一个购物车
        if (cart == null){
            cart = new Cart();
            httpSession.setAttribute("cart",cart);
        }
        Product product = productService.getById(cartItem.getProductId());
        cartItem.setName(product.getProductName());
        cartItem.setPrice(product.getProductPrice());
        cartItem.setTotalPrice(cartItem.getCount()*product.getProductPrice());
        cart.addItem(cartItem);
        //首页产生购物车，如果无货源，那么不会显示出来。
        return new Result(200,"添加成功");
    }
}
